<template>
  <div class="interested-talent-container">
    <div class="filter-container">
      <el-row :gutter="20">
        <el-col :span="4">
          <el-input
            v-model="keywordFilter"
            placeholder="请输入姓名/期望职位"
            clearable
            @change="handleFilterChange"
            @keyup.enter="handleFilterChange"
          ></el-input>
        </el-col>
        <el-col :span="4">
          <el-select
            v-model="industryFilter"
            placeholder="请选择期望行业"
            clearable
            @change="handleFilterChange"
          >
            <el-option label="全部" value=""></el-option>
            <el-option
              v-for="industry in uniqueIndustries"
              :key="industry"
              :label="industry"
              :value="industry"
            ></el-option>
          </el-select>
        </el-col>
        <el-col :span="4">
          <el-select
            v-model="educationFilter"
            placeholder="请选择学历"
            clearable
            @change="handleFilterChange"
          >
            <el-option label="全部" value=""></el-option>
            <el-option label="大专" value="COLLEGE"></el-option>
            <el-option label="本科" value="UNDERGRADUATE"></el-option>
            <el-option label="硕士" value="MASTER"></el-option>
            <el-option label="博士" value="DOCTOR"></el-option>
          </el-select>
        </el-col>
        <el-col :span="2">
          <el-button @click="handleReset()"> 重置 </el-button>
        </el-col>
      </el-row>
    </div>

    <div class="talent-list">
      <el-table
        :data="filteredTalents"
        border
        stripe
        :loading="loading"
        style="width: 100%"
      >
        <el-table-column
          type="index"
          label="序号"
          width="80"
          align="center"
        ></el-table-column>

        <!-- 姓名 -->
        <el-table-column prop="name" label="姓名"></el-table-column>

        <!-- 学历 -->
        <el-table-column prop="education" label="学历" align="center">
          <template #default="scope">{{
            formatEducation(scope.row.education)
          }}</template>
        </el-table-column>

        <!-- 期望行业 -->
        <el-table-column
          prop="expectedIndustry"
          label="期望行业"
          align="center"
        ></el-table-column>

        <!-- 期望职位 -->
        <el-table-column
          prop="expectedPosition"
          label="期望职位"
          align="center"
        ></el-table-column>

        <!-- 期望薪资 -->
        <el-table-column prop="expectedSalary" label="期望薪资" align="center">
          <template #default="scope">
            {{ scope.row.expectedSalary }}k/月
          </template>
        </el-table-column>

        <!-- 所在地 -->
        <el-table-column
          prop="location"
          label="所在地"
          width="150"
          align="center"
        ></el-table-column>
        <el-table-column label="操作" width="120" align="center">
          <template #default="scope">
            <el-button
              type="text"
              @click="communicate(scope.row.userId, scope.row.name)"
              :loading="scope.row.communicating"
            >
              <i class="el-icon-chat-dot-round"></i> 沟通
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 空状态 -->
    <div v-if="allTalents.length === 0 && !loading" class="empty-state">
      <p>暂无感兴趣的人才</p>
      <el-button
        type="primary"
        @click="$router.push({ name: 'company-seeker' })"
        >去发现人才</el-button
      >
    </div>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 30]"
        :page-size="pageSize"
        :total="totalTalents"
        layout="total, sizes, prev, pager, next, jumper"
        v-if="allTalents.length > 0"
      ></el-pagination>
    </div>
  </div>
</template>

<script>
import { getInterestedSeekerList } from "@/api/recuriter/applicationManagement";
import { formatTime } from "@/util/get-time";
export default {
  data() {
    return {
      keywordFilter: "",
      industryFilter: "",
      educationFilter: "",

      // 分页参数
      currentPage: 1,
      pageSize: 10,
      totalTalents: 0,

      // 原始数据
      allTalents: [],
      loading: false,
      currentId: 1,
      open: false,
    };
  },

  computed: {
    uniqueIndustries() {
      const industries = this.allTalents.map(
        (talent) => talent.expectedIndustry
      );
      return [...new Set(industries)].filter(Boolean);
    },

    // 筛选后的人才列表（分页前）
    filteredTalentsBeforePage() {
      return this.allTalents.filter((talent) => {
        // 1. 关键词筛选（姓名/期望职位）
        if (this.keywordFilter) {
          const keyword = this.keywordFilter.toLowerCase();
          const matchName = talent.name?.toLowerCase().includes(keyword);
          const matchPosition = talent.expectedPosition
            ?.toLowerCase()
            .includes(keyword);
          if (!matchName && !matchPosition) return false;
        }

        // 2. 期望行业筛选
        if (
          this.industryFilter &&
          talent.expectedIndustry !== this.industryFilter
        ) {
          return false;
        }

        // 3. 学历筛选
        if (this.educationFilter && talent.education !== this.educationFilter) {
          return false;
        }

        return true;
      });
    },

    // 分页后的人才列表（表格最终数据源）
    filteredTalents() {
      const startIndex = (this.currentPage - 1) * this.pageSize;
      const endIndex = startIndex + this.pageSize;
      return this.filteredTalentsBeforePage.slice(startIndex, endIndex);
    },
  },

  created() {
    this.loadInterestedTalents();
  },

  methods: {
    async communicate(userId, name) {
      const talentIndex = this.allTalents.findIndex((t) => t.userId === userId);
      if (talentIndex !== -1) {
        this.$set(this.allTalents[talentIndex], "communicating", true);
      }

      try {
        const currentTime = formatTime();
        await this.$store.dispatch("chat/sendChatMessage", {
          toUserId: userId,
          fromRole: "recruiter",
          content:
            this.$store.state.recruiter.Greeting ||
            "您好，我们对您很感兴趣，想和您进一步沟通一下职位详情。",
          toRole: "seeker",
        });

        this.$confirm(
          `已向${name}发送沟通请求,如需修改打招呼内容，请在【账号与安全中心-设置招呼语】页面修改`,
          {
            confirmButtonText: "继续沟通",
            cancelButtonText: "留在此页",
            type: "warning",
          }
        )
          .then(() => {
            this.$router.push({
              name: "company-chat",
              params: { userId },
            });
          })
          .catch(() => {});
      } catch (error) {
        console.error("发送消息失败:", error);
        this.$message.error("消息发送失败，请稍后再试");
      } finally {
        if (talentIndex !== -1) {
          this.$set(this.allTalents[talentIndex], "communicating", false);
        }
      }
    },
    async loadInterestedTalents() {
      this.loading = true;
      try {
        const response = await getInterestedSeekerList();
        if (response.data.code === 201) {
          this.allTalents = response.data.data;
          this.totalTalents = this.allTalents.length;
        } else {
          this.$message.error(response.msg || "加载人才数据失败");
          this.allTalents = [];
        }
      } catch (error) {
        console.error("加载人才数据失败：", error);
        this.$message.error("加载人才数据失败，请重试");
        this.allTalents = [];
      } finally {
        this.loading = false;
      }
    },

    // 筛选条件变化时重置页码
    handleFilterChange() {
      this.currentPage = 1;
    },

    // 分页大小变化
    handleSizeChange(size) {
      this.pageSize = size;
      this.currentPage = 1;
    },

    // 页码变化
    handleCurrentChange(page) {
      this.currentPage = page;
    },

    // 格式化学历显示（后端返回的是英文，转为中文）
    formatEducation(education) {
      const map = {
        COLLEGE: "大专",
        UNDERGRADUATE: "本科",
        MASTER: "硕士",
        DOCTOR: "博士",
        OTHER: "其他",
      };
      return map[education] || education;
    },
    handleReset() {
      this.loading = true;
      this.keywordFilter = "";
      this.industryFilter = "";
      this.educationFilter = "";
      this.currentPage = 1;
      setTimeout(() => {
        this.loadInterestedTalents();
      }, 0);
    },
  },
};
</script>

<style scoped>
.interested-talent-container {
  padding: 20px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  min-height: calc(100vh - 60px);
}

.filter-container {
  margin-bottom: 20px;
  padding: 15px;
  border-radius: 4px;
}

.talent-list {
  margin-bottom: 20px;
}

.pagination-container {
  text-align: right;
  margin-top: 15px;
}

.empty-state {
  text-align: center;
  padding: 60px 0;
}

.empty-state img {
  width: 120px;
  height: 120px;
  margin-bottom: 20px;
}

.empty-state p {
  color: #909399;
  margin-bottom: 20px;
}

/* 表格样式优化 */
::v-deep .el-table th {
  background-color: #f8f9fa;
  font-weight: 500;
}

::v-deep .el-table td {
  vertical-align: middle;
}

/* 响应式调整 */
@media (max-width: 1200px) {
  .filter-container {
    overflow-x: auto;
  }
  .el-row {
    flex-wrap: nowrap;
  }
}

@media (max-width: 768px) {
  .interested-talent-container {
    padding: 10px;
  }
  .el-row {
    flex-wrap: wrap;
  }
  .el-col {
    flex: 0 0 100%;
    margin-bottom: 10px;
  }
  .pagination-container {
    text-align: center;
  }
}
</style>